package com.iwomy.secureplat.admin.utils;

import cn.hutool.core.util.StrUtil;
import com.iwomy.secureplat.admin.api.entity.SysDept;
import com.iwomy.secureplat.admin.api.entity.SysRole;
import com.iwomy.secureplat.admin.api.feign.RemoteDataScopeService;
import com.iwomy.secureplat.common.core.constant.SecurityConstants;
import com.iwomy.secureplat.common.core.util.RetOps;
import com.iwomy.secureplat.common.core.util.SpringContextHolder;
import com.iwomy.secureplat.common.data.datascope.DataScopeTypeEnum;
import com.iwomy.secureplat.common.security.service.SecureplatUser;
import com.iwomy.secureplat.common.security.util.SecurityUtils;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.GrantedAuthority;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@UtilityClass
public class DataScopeUtils {
	RemoteDataScopeService dataScopeService = SpringContextHolder.getBean(RemoteDataScopeService.class);

	/**
	 * 获取当前用户的数据权限，查询的时候.in(xxxclass::getDeptId,lsist)
	 *
	 * @return
	 */
	public List<Long> getList() {
		SecureplatUser user = SecurityUtils.getUser();
		List<String> roleIdList = user.getAuthorities().stream().map(GrantedAuthority::getAuthority)
				.filter(authority -> authority.startsWith(SecurityConstants.ROLE))
				.map(authority -> authority.split(StrUtil.UNDERLINE)[1]).collect(Collectors.toList());

		SysRole role = RetOps.of(dataScopeService.getRoleList(roleIdList))
				.getData()
				.orElseGet(Collections::emptyList)
				.stream()
				.min(Comparator.comparingInt(SysRole::getDsType)).orElse(null);
		// @formatter:on
		// 角色有可能已经删除了

		Integer dsType = role.getDsType();
		// 查询全部
		List<Long> deptList = new ArrayList<>();


		// 查询本级及其下级
		if (DataScopeTypeEnum.OWN_CHILD_LEVEL.getType() == dsType) {
			// @formatter:off
			List<Long> deptIdList = RetOps.of(dataScopeService.getDescendantList(user.getDeptId()))
					.getData()
					.orElseGet(Collections::emptyList)
					.stream()
					.map(SysDept::getDeptId).collect(Collectors.toList());
			// @formatter:on
			deptList.addAll(deptIdList);
		}
		// 只查询本级
		if (DataScopeTypeEnum.OWN_LEVEL.getType() == dsType) {
			deptList.add(user.getDeptId());
		}

		return deptList;

	}


}
